package handler

import (
	"cinema-hub/models"
	"github.com/gin-gonic/gin"
	"strconv"
)

func List(c *gin.Context) {
	var movies []*models.Movies

	page, _ := strconv.Atoi(c.Query("page"))
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(c.Query("size"))
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	if err := models.DB.Offset(offset).Limit(pageSize).Find(&movies).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": movies,
	})
	return
}
func Add(c *gin.Context) {
	userId, _ := strconv.Atoi(c.PostForm("user_id"))
	title := c.PostForm("title")
	content := c.PostForm("content")
	like, _ := strconv.Atoi(c.PostForm("like"))
	collection, _ := strconv.Atoi(c.PostForm("collection"))
	data := models.Movies{

		UserId:     userId,
		Title:      title,
		Content:    content,
		Like:       like,
		Collection: collection,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
